
package com.yimixian.app.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.Drawable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.squareup.picasso.RequestCreator;
import com.squareup.picasso.Target;
import com.ta.utdid2.android.utils.StringUtils;
import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.cart.CartManager;
import com.yimixian.app.cart.GoodsItemPresenter;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.StatConstants;
import com.yimixian.app.common.WebViewActivity;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.goods.GoodDetailActivity;
import com.yimixian.app.model.GoodsItem;
import com.yimixian.app.util.Strings;
import com.yimixian.app.util.UiUtils;
import com.ymx.sdk.util.DensityUtils;
import com.ymx.sdk.util.DeviceUtils;

import java.io.IOException;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * 活动专场item Created by zhilian-2 on 2015/10/29.
 */
public class SessionItemView extends RelativeLayout {

    @InjectView(R.id.list_item)
    RelativeLayout listItem;
    @InjectView(R.id.goods_image)
    ImageView mGoodsImage;
    @InjectView(R.id.good_name)
    TextView mTitleText;
    @InjectView(R.id.rest_count)
    TextView leftCount;
    @InjectView(R.id.once_count)
    TextView onceCount;
    @InjectView(R.id.start_sale)
    TextView startSale;
    @InjectView(R.id.image_top_left)
    ImageView mPromotionImage;
    @InjectView(R.id.lin_right_top)
    LinearLayout linRightTop;
    @InjectView(R.id.buy_price_text)
    TextView buyPriceText;
    @InjectView(R.id.old_price_text)
    TextView oldPriceText;
    @InjectView(R.id.control_area)
    FrameLayout mControlArea;
    @InjectView(R.id.count_down)
    TextView countDown;
    @InjectView(R.id.tuan_button)
    TextView mTuanButton;
    @InjectView(R.id.control_tuan_area)
    FrameLayout mControlTuanArea;
    @InjectView(R.id.old_rmb)
    TextView mOldRmb;

    private GoodsItem mGoodsItem;
    private DataManager mDataManager;
    private int mScreenWidth;
    private GoodsItemPresenter.OnPlusButtonClickListener mOnPlusButtonClickListener;

    private PlusMinusIcon mPlusMinusIcon;
    int mScreenWidht;
    private Target target;

    public SessionItemView(Context context) {
        super(context);
        initView();
    }

    public SessionItemView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public SessionItemView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    private void initView() {
        LayoutInflater.from(getContext()).inflate(R.layout.session_item, this);
        ButterKnife.inject(this);
        mScreenWidht = DeviceUtils.getScreenWidth(getContext());
        mDataManager = DataManager.getInstance();
    }

    public void setOnPlusButtonClickListener(GoodsItemPresenter.OnPlusButtonClickListener listener) {
        mOnPlusButtonClickListener = listener;
    }

    public void bindData(final GoodsItem goodsItem) {
        if (goodsItem == null) {
            mGoodsItem = null;
            return;
        }

        int count = 0;
        if (CartManager.getInstance().mCartGoodsItems != null && goodsItem != null) {
            count = CartManager.getInstance().mCartGoodsItems.get(goodsItem.id) == null ? 0
                    : Integer
                            .parseInt(CartManager.getInstance().mCartGoodsItems.get(goodsItem.id).count);
        }
        if (mPlusMinusIcon == null) {
            mPlusMinusIcon = new PlusMinusIcon(SystemFramework.getInstance().getGlobalContext(),
                    goodsItem, Constants.STATE_SESSIONLIST_BUTTON_BROADCAST);
            mControlArea.addView(mPlusMinusIcon);
            mPlusMinusIcon.setQuantity(count);
            mPlusMinusIcon.setOnPlusButtonClickListener(mOnPlusButtonClickListener);
        } else {
            mPlusMinusIcon.updateGoodsItem(goodsItem);
            mPlusMinusIcon.setQuantity(count);
        }

        mGoodsItem = goodsItem;

        float height = mGoodsItem.imgRatio == 0 ? DensityUtils.dp2px(getContext(), 125) :
                mScreenWidht / mGoodsItem.imgRatio;
        LayoutParams params = new LayoutParams(
                LayoutParams.MATCH_PARENT, (int) height);
        // mGoodsImage.setLayoutParams(params);
        // params.bottomMargin = DensityUtils.dp2px(getContext(), 5);
        listItem.setLayoutParams(params);

        // RelativeLayout.LayoutParams paramsImage = new
        // RelativeLayout.LayoutParams(
        // LayoutParams.MATCH_PARENT, (int) height);
        // mGoodsImage.setLayoutParams(paramsImage);

        String imgUrl = mDataManager.getImageUrl(goodsItem.img, mScreenWidth / 2);
        Picasso picasso = Picasso.with(getContext());
        picasso.load(imgUrl).placeholder(R.drawable.image_left_default).into(mGoodsImage);
        if(target == null){
            target = new Target() {
                @Override
                public void onBitmapLoaded(Bitmap back, Picasso.LoadedFrom from) {
                    int screenWidth = getResources().getDisplayMetrics().widthPixels;
                    int width = back.getWidth() > screenWidth ? screenWidth : back.getWidth();
                    int height = back.getHeight();
                    float radius = height / 2;
                    float centerX = height / 2;
                    float centerY = height / 2;
                    Bitmap bm_circle = Bitmap.createBitmap(height, height, Bitmap.Config.ARGB_8888);
                    Canvas canvas_circle = new Canvas(bm_circle);
                    Paint paint = new Paint();
                    paint.setAntiAlias(true);
                    canvas_circle.drawCircle(centerX, centerY, radius, paint);
                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
                    canvas_circle.drawBitmap(back, 0, 0, paint);
                    Matrix matrix = new Matrix();
                    float temp = getResources().getDisplayMetrics().density * 40;
                    float ratio = temp / height;
                    matrix.setScale(ratio, ratio);
                    mPlusMinusIcon.setShowBack(Bitmap.createBitmap(bm_circle, 0, 0, height, height, matrix, false));
                    bm_circle.recycle();
                }

                @Override
                public void onBitmapFailed(Drawable errorDrawable) {}

                @Override
                public void onPrepareLoad(Drawable placeHolderDrawable) {}
            };
        }
        picasso.load(imgUrl).placeholder(R.drawable.image_left_default).into(target);

        if (Strings.isNullOrEmpty(mGoodsItem.promotionImg)) {
            mPromotionImage.setVisibility(GONE);
        } else {
            mPromotionImage.setVisibility(VISIBLE);
            int size = getResources().getDimensionPixelSize(R.dimen.promotion_image_size);
            picasso.load(mDataManager.getImageUrl(mGoodsItem.promotionImg, size)).into(
                    mPromotionImage);
        }

        SpannableStringBuilder builder;

        // mTextArea.setVisibility(VISIBLE);
        // 判断是否为团购商品
        if (goodsItem.isBuyingGroup == 1) {
            mControlArea.setVisibility(GONE);
            mControlTuanArea.setVisibility(View.VISIBLE);
            builder = new SpannableStringBuilder(Constants.YUAN
                    + goodsItem.buyingGroupPrice);
            if (goodsItem.shouldBuyCount < 1) {
                mTuanButton.setBackgroundResource(R.drawable.rounded_button_disabled);
                mTuanButton.setEnabled(true);
            } else {
                mTuanButton.setBackgroundResource(R.drawable.orange_button_bg);
                mTuanButton.setEnabled(true);
            }
        } else {
            mControlTuanArea.setVisibility(GONE);
            mControlArea.setVisibility(View.VISIBLE);
            builder = new SpannableStringBuilder(Constants.YUAN
                    + goodsItem.unitPrice);
        }

        mTuanButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                startTuan(goodsItem);
            }
        });

        mTitleText.setText(goodsItem.name);

        String buyingGroupCount = goodsItem.isBuyingGroup == 1 ? goodsItem.buyingGroupCount
                + "人团  " : "";
        if (goodsItem.isBuyingGroup == 1) {
            onceCount.setText(buyingGroupCount + "  " +
                    (StringUtils.isEmpty(goodsItem.unitDesc) ? "" : goodsItem.unitDesc));
        } else {
            onceCount.setText(StringUtils.isEmpty(goodsItem.unitDesc) ? "" : goodsItem.unitDesc);
        }

        leftCount.setText(StringUtils.isEmpty(goodsItem.stockCount) ? "" : goodsItem.stockCount);
        // onceCount.setText(StringUtils.isEmpty(goodsItem.unitDesc) ? "" :
        // goodsItem.unitDesc);
        // startSale.setText(StringUtils.isEmpty(goodsItem.saleStatus) ? "" :
        // goodsItem.saleStatus);
        if (StringUtils.isEmpty(goodsItem.saleStatus)) {
            countDown.setVisibility(GONE);
        } else {
            countDown.setVisibility(VISIBLE);
            countDown.setText(goodsItem.saleStatus);
        }

        buyPriceText.setText(StringUtils.isEmpty(goodsItem.unitPrice) ? "" : goodsItem.unitPrice);
       if (TextUtils.isEmpty(goodsItem.unitOldPrice)){
           oldPriceText.setVisibility(View.INVISIBLE);
           mOldRmb.setVisibility(View.INVISIBLE);
       }else {
           oldPriceText.setVisibility(View.VISIBLE);
           mOldRmb.setVisibility(View.VISIBLE);
       }
        oldPriceText.setText(StringUtils.isEmpty(goodsItem.unitOldPrice) ? ""
                : goodsItem.unitOldPrice);
        oldPriceText.setPaintFlags(oldPriceText.getPaintFlags()
            | Paint.STRIKE_THRU_TEXT_FLAG);

        if (!Strings.isNullOrEmpty(goodsItem.descUrl)) {
            listItem.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (goodsItem.isBuyingGroup == 0) {
                        MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                                StatConstants.HOME_GOOD_ITEM_IMAGE_CLICK);
                        ((Activity)getContext()).startActivityForResult(GoodDetailActivity.buildIntent(getContext(),
                                String.valueOf(goodsItem.id)), 1000);
//                        getContext().startActivity(
//                                GoodDetailActivity.buildIntent(getContext(),
//                                        String.valueOf(goodsItem.id)));
                    } else {
                        startTuan(goodsItem);
                    }

                }
            });
        } else {
            mGoodsImage.setOnClickListener(null);
        }
    }

    private void startTuan(GoodsItem goodsItem) {
        if (goodsItem != null) {
            if (goodsItem.shouldBuyCount > 0) {
                startTuanWebActivity(goodsItem);
            } else {
                if (!TextUtils.isEmpty(goodsItem.countZeroReason)) {
                    UiUtils.showToast(goodsItem.countZeroReason);
                    return;
                }
            }
        }
    }

    private void startTuanWebActivity(GoodsItem goodsItem) {
        Intent intent = new Intent(getContext(), WebViewActivity.class);
        intent.putExtra(WebViewActivity.EXTRA_URL, goodsItem.descUrl);
        getContext().startActivity(intent);
    }
}
